# Create your views here.

from django.views.generic import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse
from django.forms.models import inlineformset_factory

from formulario_simple.models import (Jugador, Operativo, RegistroDeVictima)


# ABM para jugador
class ModificarJugadorView(UpdateView):
    model = Jugador
    
    def get_object(self):
        try:
            obj = super(ModificarJugadorView, self).get_object()
        except AttributeError:
            obj = None
        return obj
    
    def get_success_url(self):
        return reverse('formulario_simple:crear_jugador')

class EliminarJugadorView(DeleteView):
    model = Jugador
    
    def get_success_url(self):
        return reverse('formulario_simple:crear_jugador')


# Pueba de formulario inline de un manytomany, con "raiz" a la clase que NO tiene
# declarado el manytomany

class ModificarOperativoView(UpdateView):
    model = Operativo
    
    def get_context_data(self, **kwargs):
        context_data = super(ModificarOperativoView, self).get_context_data(**kwargs)
        RegistroDeVictimaInlineFormSet = inlineformset_factory(
            Operativo,
            RegistroDeVictima.operativos.through,
            extra=2,
        )
        context_data.update({'formset': RegistroDeVictimaInlineFormSet(instance=self.object)})
        return context_data
    
    def post(self, request, *args, **kwargs):
        response = super(ModificarOperativoView, self).post(request, *args, **kwargs)
        RegistroDeVictimaInlineFormSet = inlineformset_factory(
            Operativo,
            RegistroDeVictima.operativos.through,
            extra=2,
        )
        formset = RegistroDeVictimaInlineFormSet(request.POST, request.FILES, instance=self.object)
        if formset.is_valid():
            formset.save()
        
        return response
    
    def get_success_url(self):
        return reverse('formulario_simple:editar_operativo',kwargs={'pk':1})